<template>
  <div>
    <canvas id="can"
            width="150"
            height="40"
            @click="changeVeri()"></canvas>
  </div>
</template>

<script>
import { getVeri } from '../../api/login'
export default {
  name: 'Ljfvue2011Veri',

  data () {
    return {
      code: "abcd"
    };
  },
  created () {
    this.makeVeri();
  },
  mounted () {
    console.log(this.ranColor());
    console.log(this.ranDom(10, 20))
    this.draw();
  },

  methods: {
    changeVeri () {//点击获取验证码
      this.makeVeri();
    },
    async makeVeri () {
      // 获取验证码接口的调用
      var res = await getVeri();
      console.log(res)
      this.code = res.data.data;
      this.draw();//获取新的验证码重新绘制
    },
    // 随机函数
    ranDom (a, b) { //a-b之间的随机数
      return Math.floor(Math.random() * (b - a + 1) + a)
    },
    // 随机颜色
    ranColor () {
      return "#" + Math.floor(Math.random() * 0xFFFFFF).toString(16)
    },
    draw () { //绘制验证码方法
      var can = document.getElementById("can");
      var c = can.getContext("2d");
      // 清空画布
      c.clearRect(0, 0, 150, 40);
      // 绘制干扰线
      // for (var i = 0; i < 20; i++) {
      //   c.beginPath()
      //   c.moveTo(this.ranDom(0, 150), this.ranDom(0, 40))
      //   c.lineTo(this.ranDom(0, 150), this.ranDom(0, 40))
      //   c.strokeStyle = this.ranColor();
      //   c.stroke();
      // }
      // 绘制干扰点
      // for (var y = 0; y < 30; y++) {
      //   c.beginPath()
      //   var lx = this.ranDom(0, 150);
      //   var ly = this.ranDom(0, 40);
      //   c.moveTo(lx, ly)
      //   c.lineTo(lx + 1, ly + 1)
      //   c.strokeStyle = this.ranColor();
      //   c.stroke();
      // }
      // 绘制文本
      // c.rotate(this.ranDom(-5, 5) * Math.PI / 180);
      for (var k = 0; k < this.code.length; k++) {
        c.font = "25px 黑体";
        c.fillText(this.code[k], 30 * k + this.ranDom(5, 20), this.ranDom(20, 30))
        c.fillStyle = this.ranColor();
        c.stroke()
      }
    }
  },
};
</script>

<style lang="less" scoped>
#can {
  background: #ccc;
}
</style>